<template>
	<view class="container">
		<uni-search-bar class='search' :placeholder="searchPlaceholder" v-model="searchValue" @input='onInput'></uni-search-bar>
		<view class="list">
			<uni-list :border="listBorder">
				<uni-list-item :border="listItemBorder" :title="item.text" :key="index" clickable v-for="(item, index) in showList" @click="onClick(item)" />
			</uni-list>
		</view>
	</view>
</template>
<script>
	export default{
		data(){
			return {
				searchValue: '',
				searchList: [],
			}
		},
		props: {
			searchPlaceholder: {
				type:String,
				default: '请输入搜索内容'
			},
			listBorder: {
				type:Boolean,
				default: true
			},
			listItemBorder: {
				type:Boolean,
				default: true
			},
			list: {
				type: Array,
				default () {
					return [
						{
							id: 0,
							text: '00'
						},
						{
							id: 1,
							text: '11'
						},
					]
				}
			}
		},
		watch:{
			list(newValue){
				console.log(newValue, 'aaa');
				
			}
		},
		computed:{
			showList(){
				if (this.searchValue) {
					return this.searchList;
				} else {
					return this.list
				}
			}
		},
		methods:{
			onInput(e){
				console.log(e, 'e');
				this.searchList = this.list.filter(i => {
					return this.fuzzyMatch(i.text, this.searchValue)
				})
			},
			onClick(e){
				console.log(e, 'e');
				this.$emit('click', e);
			},
			// 模糊匹配
			fuzzyMatch(str, key){
			    let index = -1, flag = false;
			    for(var i = 0, arr = key.split(""); i < arr.length; i++ ){
			        //有一个关键字都没匹配到，则没有匹配到数据
			        if(str.indexOf(arr[i]) < 0){
			            break;
			        }else{
			            let match = str.matchAll(arr[i]);
			            let next = match.next();
			            while (!next.done){
			                if(next.value.index > index){
			                    index = next.value.index;
			                    if(i === arr.length - 1){
			                        flag = true
			                    }
			                    break;
			                }
			                next = match.next();
			            }
			
			        }
			    }
			    return flag
			}
		}
	}
</script>
<style scoped lang="scss">
	.container{
		width: 100%;
	}
</style>
